package top.heliming.youyou.listener;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import top.heliming.youyou.properties.SmsProperties;
import top.heliming.youyou.util.SmsUtils;

/**
 * description: //TODO
 *
 * @author: heliming
 * @date:2019/06/08 下午 2:41
 */
@Component
@EnableConfigurationProperties(SmsProperties.class)
public class SmsListener {
  static final Logger logger = LoggerFactory.getLogger(SmsListener.class);

  @Autowired
  private SmsUtils smsUtils;

  @Autowired
  private SmsProperties prop;

  @RabbitListener(bindings = @QueueBinding(
      value = @Queue(value = "leyou.sms.queue", durable = "true"),
      exchange = @Exchange(value = "leyou.sms.exchange",
          ignoreDeclarationExceptions = "true"),
      key = {"sms.verify.code"}))
  public void listenSms(Map<String, String> msg) throws Exception {
    if (msg == null || msg.size() <= 0) {
      // 放弃处理
      return;
    }
    String phone = msg.get("phone");
    String code = msg.get("code");

    if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)) {
      // 放弃处理
      return;
    }
    try {
      // 发送消息
      SendSmsResponse resp = this.smsUtils.sendSms(phone, code,
          prop.getSignName(),
          prop.getVerifyCodeTemplate());
    }catch (Exception e){
      logger.info("发送验证码失败："+e.getMessage());
    }
  }
}
